import 'package:flutter/material.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';

import '../common/api_service.dart';
import '../common/constants.dart';
import '../model/pipe_model.dart';
import '../pages/pipe_data_list_page.dart';
import '../utils/screen_util.dart';
import 'empty_view.dart';

class MinePipeListView extends StatefulWidget {
  final String uid;

  const MinePipeListView({super.key, required this.uid});

  @override
  State<MinePipeListView> createState() => _MinePipeListViewState();
}

class _MinePipeListViewState extends State<MinePipeListView> with AutomaticKeepAliveClientMixin {
  final List<PipeModel> _pipeList = [];
  bool _isLoading = false;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();

    _getUserPipeList();
  }

  void _getUserPipeList() {
    ApiService().getUserPipeList(widget.uid, (list) {
      setState(() {
        _isLoading = false;
        _pipeList.clear();
        _pipeList.addAll(list);
      });
    }, () {
      _isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    final screenWidth = ScreenUtil.getScreenWidth(context);
    var width = (screenWidth - 12.0) * 0.5;
    var height = width * 16 / 11;
    var h = height + 70;
    double ratio = width / h;

    return _isLoading
        ? Center(
            child: LoadingAnimationWidget.progressiveDots(
              color: Constants.themeColor,
              size: 30,
            ),
          )
        : (_pipeList.isNotEmpty
            ? GridView.builder(
                shrinkWrap: true,
                padding: const EdgeInsets.all(4),
                physics: const NeverScrollableScrollPhysics(),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  mainAxisSpacing: 0,
                  crossAxisSpacing: 4,
                  childAspectRatio: ratio,
                ),
                itemCount: _pipeList.length,
                itemBuilder: (context, itemIndex) {
                  var pipe = _pipeList[itemIndex];
                  return HomePipeCard(width: width, height: height, pipe: pipe, showSummary: false);
                },
              )
            : const EmptyView());
  }
}
